#include <Windows.h>
#include <tchar.h>
#include <stdio.h>
#include "resource.h"
#include "Variable.h"



void InitStep2(HWND hDlg)
{
	//init window
	int iScreenWidth = GetSystemMetrics(SM_CXFULLSCREEN);
	int iScreenHeight = GetSystemMetrics(SM_CYFULLSCREEN);


	RECT rect;
	GetWindowRect(hDlg,&rect);
	
	LONG width = rect.right;
	LONG height = rect.bottom;
	int inewLeft = (iScreenWidth-width)/2;
	int inewTop = (iScreenHeight-height)/2;

	MoveWindow(hDlg,inewLeft,inewTop,width,height,FALSE);


	HWND installRemedy = GetDlgItem(hDlg,IDC_CHECK1);
	HWND installAddin = GetDlgItem(hDlg,IDC_CHECK2);
	if(Step2Data.InstallNRemedy){
		if(installRemedy != NULL)
			SendMessage(installRemedy, BM_SETCHECK, BST_CHECKED, 0); 
	}
	else
	{
		if(installRemedy != NULL)
			SendMessage(installRemedy, BM_SETCHECK, BST_UNCHECKED, 0); 
	}

	if(Step2Data.InstallAddin){
		if(installAddin != NULL)
			SendMessage(installAddin, BM_SETCHECK, BST_CHECKED, 0); 
	}
	else
	{
		if(installAddin != NULL)
			SendMessage(installAddin, BM_SETCHECK, BST_UNCHECKED, 0); 
	}

}

void CheckInstallRemedy(BOOL Checked)
{
	Step2Data.InstallNRemedy = Checked;
}

void CheckInstallAddin(BOOL Checked)
{
	Step2Data.InstallAddin = Checked;
}

/*input :  folder\folder\file
*/
BOOL CheckFileByRelativePath(LPCTSTR fileName,LPCTSTR modulePath)
{
	size_t len = _tcslen(modulePath);
	if(len > 0){
		size_t i = len-1;
		for( ; i >= 0 ;i--){
			if(modulePath[i] == '\\')
				break;
		}
		if(i <= 0) return FALSE;

		TCHAR tmp[MAX_PATH+1];
		_tcscpy(tmp,modulePath);
		tmp[i+1] = TEXT('\0');
		_tcscat(tmp,fileName);

		WIN32_FIND_DATA FindFileData;
		HANDLE hFind = FindFirstFile(tmp,&FindFileData);
		if(INVALID_HANDLE_VALUE == hFind){
			return FALSE;
		}
		else{
			FindClose(hFind);
			return TRUE;
		}
	}
	return FALSE;
}

/*input :  folder\folder\file
			Driver:\folder\folder
*/
BOOL CopyFileByRelativePath(LPCTSTR lpSrcfileName,LPCTSTR lpDestargetPath,LPCTSTR lpModulePath)
{
	size_t len = _tcslen(lpModulePath);
	if(len > 0){
		size_t i = len-1;
		for( ; i >= 0 ;i--){
			if(lpModulePath[i] == '\\')
				break;
		}
		if(i <= 0) return FALSE;

		TCHAR tmp[MAX_PATH+1];
		_tcscpy(tmp,lpModulePath);
		tmp[i+1] = TEXT('\0');
		_tcscat(tmp,lpSrcfileName);

		TCHAR tmpT[MAX_PATH+1] = {0};
		_tcscpy(tmpT,lpDestargetPath);

		TCHAR* p = &tmp[_tcslen(tmp)-1];
		while((*p--) != '\\');

		_tcscat(tmpT,p+2);

		return CopyFile(tmp,tmpT,FALSE);
	}
	return FALSE;
}


BOOL FolderExist(LPCTSTR szPath)
{
     WIN32_FIND_DATA wfd;
     BOOL rValue = FALSE;
	 size_t ccSrcLen = _tcslen(szPath);
	 TCHAR* szTempPath = new TCHAR[ccSrcLen+1];
	 _tcscpy(szTempPath,szPath);
	 if(szTempPath[_tcslen(szTempPath)-1] == TEXT('\\'))
	 {
		 szTempPath[_tcslen(szTempPath)-1] = TEXT('\0');
	 }
     HANDLE hFind = FindFirstFile(szTempPath, &wfd);
	 if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){
		 rValue = TRUE;   
	 }
     FindClose(hFind);
	 delete[] szTempPath;
	 return rValue;
}

BOOL DoInstall()
{
	TCHAR szModulePath[MAX_PATH+1];
	GetModuleFileName(_hInstance,szModulePath,MAX_PATH+1);

	UCHAR cLoop = 1;
	TCHAR szMsg[512] = {0};
	BOOL rValue = FALSE;
	LPBYTE lpbOrignalEnvPath = NULL;
	TCHAR* szTargetEnvPath = NULL;
	TCHAR* szHomeDrive = NULL;
	TCHAR* szHomePath = NULL;
	TCHAR* szTargetAddinPath = NULL;


	while(cLoop--){
		if(Step2Data.InstallNRemedy)
		{
			//check files in NRemedy.Core folder
			int fileCount = sizeof(FileInCore)/sizeof(int);
			int i = 0,j = 0;
			for(; i < fileCount ; i++)
			{
				if(!CheckFileByRelativePath(FileInCore[i],szModulePath)){
					_sntprintf(szMsg,512,
						TEXT("%s is missing,install package may be broken."),FileInCore[i]);
					break;
				}
			}
			if(i != fileCount) break;
			//create target folder C:\Program Files\Wicresoft.NRemedy
			CreateDirectory(NRemedyCoreTarget,NULL);
			//copy files into target folder
			for( ; j < fileCount ; j++){
				if(!CopyFileByRelativePath(FileInCore[j],NRemedyCoreTarget,szModulePath))
				{
					DWORD dwError = GetLastError();
					_sntprintf(szMsg,512,
						TEXT("Copying %s failed.error code : %d"),FileInCore[j],dwError);
					break;
				}
			}
			if(j != fileCount) break;

			//regist system enviroment variable (Path)
			HKEY hEnvKEY;
			if(RegOpenKeyEx(HKEY_LOCAL_MACHINE
				,TEXT("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\\")
				,0
				,KEY_ALL_ACCESS
				,&hEnvKEY) != ERROR_SUCCESS)
			{
				DWORD dwError = GetLastError();
				_sntprintf(szMsg,512,
					TEXT("Open environment failed.error code : %d"),dwError);
				break;
			}

			DWORD dwType = REG_EXPAND_SZ;
			DWORD cbData = 0;
			if(RegQueryValueEx(hEnvKEY,TEXT("Path"),NULL,&dwType,NULL,&cbData) != ERROR_SUCCESS)
			{
				DWORD dwError = GetLastError();
				_sntprintf(szMsg,512,
					TEXT("Get path failed.error code : %d"),dwError);
				break;
			}
			lpbOrignalEnvPath = new BYTE[cbData];
			RegQueryValueEx(hEnvKEY,TEXT("Path"),NULL,&dwType,lpbOrignalEnvPath,&cbData);
			TCHAR* szOrignalEnvPath = (TCHAR*)lpbOrignalEnvPath;
			//should append ;C:\Program Files\Wicresoft.NRemedy
			if(_tcsstr(szOrignalEnvPath,NRemedyCoreTarget) == NULL)
			{
				size_t baselen = _tcslen(szOrignalEnvPath)+ _tcslen(NRemedyCoreTarget);
				szTargetEnvPath = new TCHAR[baselen + 2];
				_tcscpy(szTargetEnvPath,szOrignalEnvPath);
				_tcscat(szTargetEnvPath,TEXT(";"));
				_tcscat(szTargetEnvPath,NRemedyCoreTarget);
				szTargetEnvPath[baselen + 1] = TEXT('\0');
#ifdef _UNICODE,UNICODE
				LSTATUS status = RegSetValueEx(hEnvKEY,TEXT("Path"),NULL,dwType,(LPBYTE)szTargetEnvPath,_tcslen(szTargetEnvPath)*2+2);
#else
				LSTATUS status = RegSetValueEx(hEnvKEY,TEXT("Path"),NULL,dwType,(LPBYTE)szTargetEnvPath,_tcslen(szTargetEnvPath)+1);
#endif
				if( status
					!= ERROR_SUCCESS )
				{
					DWORD dwError = GetLastError();
					_sntprintf(szMsg,512,
						TEXT("Set Env Path failed.error code : %d,status code : %d"),dwError,status);
					break;
				}
				//SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)TEXT("Environment"));
			}
		}//install NRemedy

		if(Step2Data.InstallAddin)
		{
			//check files in /NRemedy.VS10Addin folder
			int fileCount = sizeof(FileInAddin)/sizeof(int);
			int i = 0 , j = 0;
			for(; i < fileCount ; i++){
				if(!CheckFileByRelativePath(FileInAddin[i],szModulePath))
				{
					_sntprintf(szMsg,512,
						TEXT("%s is missing,install package may be broken."),FileInAddin[i]);
					break;
				}
			}
			if(i != fileCount) break;
			//check vs2010 env
			DWORD dwSize = 0;
			dwSize = GetEnvironmentVariable(TEXT("HOMEDRIVE"),NULL,0);
			if(dwSize == 0)
			{
				DWORD dwError = GetLastError();
				_sntprintf(szMsg,512,
					TEXT("HOMEDRIVE not found.error code : %d,status code : %d"),dwError,dwSize);
				break;
			}
			szHomeDrive = new TCHAR[dwSize+1];
			GetEnvironmentVariable(TEXT("HOMEDRIVE"),szHomeDrive,dwSize+1);

			dwSize = GetEnvironmentVariable(TEXT("HOMEPATH"),NULL,0);
			if(dwSize == 0)
			{
				DWORD dwError = GetLastError();
				_sntprintf(szMsg,512,
					TEXT("HOMEPATH not found.error code : %d,status code : %d"),dwError,dwSize);
				break;
			}
			szHomePath = new TCHAR[dwSize+1];
			GetEnvironmentVariable(TEXT("HOMEPATH"),szHomePath,dwSize+1);

			szTargetAddinPath = new TCHAR[_tcslen(szHomeDrive)+_tcslen(szHomePath)+_tcslen(szTargetsub)+1];
			_tcscpy(szTargetAddinPath,szHomeDrive);
			szTargetAddinPath[_tcslen(szHomeDrive)] = TEXT('\0');
			_tcscat(szTargetAddinPath,szHomePath);
			_tcscat(szTargetAddinPath,szTargetsub);

			if(!FolderExist(szTargetAddinPath))
			{
				_sntprintf(szMsg,512,
					TEXT("VS2010 may not installed.Add-in installed failed."));
				break;
			}
			//copy addin to target folder
			if(!CopyFileByRelativePath(FileInAddin[0],szTargetAddinPath,szModulePath))
			{
				DWORD dwError = GetLastError();
				_sntprintf(szMsg,512,
					TEXT("Add-in file cannot copy to %s. error code : %d"),szTargetAddinPath,dwError);
				break;
			}
			//create target folder C:\Program Files\Wicresoft.NRemedy\en-us
			CreateDirectory(NRemedyAddinResTarget,NULL);
			if(!CopyFileByRelativePath(FileInAddin[1],NRemedyAddinResTarget,szModulePath))
			{
				DWORD dwError = GetLastError();
				_sntprintf(szMsg,512,
					TEXT("Add-in file cannot copy to %s. error code : %d"),NRemedyAddinResTarget,dwError);
				break;
			}
			//copy other files into target folder
			for(j = 2 ; j < fileCount ; j++){
				if(!CopyFileByRelativePath(FileInAddin[j],NRemedyCoreTarget,szModulePath))
				{
					DWORD dwError = GetLastError();
					_sntprintf(szMsg,512,
						TEXT("Copying %s failed.error code : %d"),FileInCore[j],dwError);
					break;
				}
			}
			if(j != fileCount) break;
			//lauch vs instance with reset command line

			//Kill the process



		}//install addin
		rValue = TRUE;
	}//while

	//msg show
	if(_tcscmp(szMsg,TEXT("")) != 0)
	{
		MessageBox(NULL,szMsg,TEXT("Install Error"),MB_OK | MB_ICONERROR);
	}

	//memory care
	if(lpbOrignalEnvPath != NULL) delete[] lpbOrignalEnvPath;
	if(szTargetEnvPath != NULL) delete[] szTargetEnvPath;
	if(szHomeDrive != NULL) delete[] szHomeDrive;
	if(szHomePath != NULL) delete[] szHomePath;
	if(szTargetAddinPath != NULL) delete[] szTargetAddinPath;

	//return
	return rValue;
}